﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Wholesaler.Models.DBModels;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;

namespace Yunzuan.Common
{
    public class CommonClass
    {
        public static Type type = typeof(Yunzuan.Common.CommonClass);
        public string searchUrl = "";

        #region  公用部分

        /// <summary>
        /// 通过参数获取所有产品并计算价格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="getProductParam"></param>
        /// <param name="searchUrl"></param>
        /// <param name="lib"></param>
        /// <returns></returns>
        private string GetProduct<T>(ref string getProductParam, string searchUrl, int lib,string key)
        {
            CommonConst.logParam = getProductParam;
            //SearchProductLogs(logParam, lib.ToString());
            try
            {
                HashParam param = Yunzuan.Foundation.Serializer.Json.Deserialize<HashParam>(getProductParam);//组装前 {"IsStock":1,"limit":100,"useDict":true}

                //现货搜索
                var responseJson = "";
                var isStock = false;
                if (param.ContainsKey("IsStock") || param.ContainsKey("IsMyStock")) //此处要多传一个IsStock或IsMyStock字段因为前段也可能搜索现货
                {
                    if (param.GetString("IsStock").ToLower().Trim() == "true" || param.GetString("IsMyStock").ToLower().Trim() == "true") //ring 如果加了现货字段传的值为：IsStock :["1"] GetBool("IsStock")会报错
                    {
                        isStock = true;//现货
                        param["Supplier"] = System.Configuration.ConfigurationManager.AppSettings["DefaultProvider"];
                        getProductParam = JsonConvert.SerializeObject(param);//组装后 {"limit":100,"useDict":true,"Supplier":"HST"}   
                    }
                }
                responseJson = AllProduct(getProductParam, searchUrl,key, "post");
                if (responseJson.Contains(".py"))
                {
                    responseJson = string.Format(CommonConst.msgInfo, "false", "远程服务错误");
                }
                else if (responseJson.Contains("result\": false"))
                {
                    responseJson = string.Format(CommonConst.msgInfo, "false", "未知错误");
                }
                else
                {
                    dynamic result = JsonConvert.DeserializeObject<T>(responseJson);
                    if (!isStock) //非现货请求计算价格,现货展示原价（底价）
                    {
                        //{\"records\": 75, \"rows\": [{\"Category
                        //计算价格
                        if (result.rows.Count > 0)
                        {
                            SysSettingInfo setting = GoodsType.GetSystemSetting(key, lib);
                            decimal disc = GoodsType.GetGlobalFancyDiscountReturn(setting); //全局折扣
                            CustomerInfo customerInfo = new CustomerInfo();
                            decimal customerDisc = 1;
                            if (param.ContainsKey("CustomerID"))//客户折扣
                            {
                                customerInfo = YZ.GetDatabase(key).Get<CustomerInfo>(Convert.ToInt32(param["CustomerID"]));
                                switch (lib)
                                {
                                    case GoodsType.Diamond:
                                        customerDisc = customerInfo.Rebate ?? 1; break;
                                    case GoodsType.Ring:
                                        customerDisc = customerInfo.RingRebate ?? 1; break;
                                    case GoodsType.Parcel:
                                        customerDisc = customerInfo.ParcelRebate ?? 1; break;
                                    case GoodsType.Gem:
                                        customerDisc = customerInfo.GemRebate ?? 1; break;
                                    case GoodsType.Emerald:
                                        customerDisc = customerInfo.EmeraldRebate ?? 1; break;
                                    case GoodsType.PrimeGolds:
                                        customerDisc = customerInfo.PrimeGoldRebate ?? 1; break;
                                }
                            }
                            //供应商折扣
                            decimal supplierDisc = 1; 
                            foreach (var item in result.rows)
                            {
                                //获取当前供应商折扣
                                switch (lib)
                                {
                                    case GoodsType.Diamond:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).Rebate ?? 1; break;
                                    case GoodsType.Ring:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).RingRebate ?? 1; break;
                                    case GoodsType.Parcel:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).ParcelRebate ?? 1; break;
                                    case GoodsType.Gem:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).GemRebate ?? 1; break;
                                    case GoodsType.Emerald:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).EmeraldRebate ?? 1; break;
                                    case GoodsType.PrimeGolds:
                                        supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,item.Supplier).PrimeGoldRebate ?? 1; break;
                                }
                                supplierDisc = supplierDisc == 0 ? 1 : supplierDisc;
                                //价格=全局，供应商，客户
                                item.Price = item.Price * disc * customerDisc * supplierDisc;
                            }
                        }
                    }
                    responseJson = string.Format(CommonConst.msgObj, "true", JsonConvert.SerializeObject(result));
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                CommonLog.GetMethodInfoAndWriteLogs(type, ex);
                return string.Format(CommonConst.msgInfo, "false", "错误信息：" + ex.ToString());
            }
        }



        /// <summary>
        /// 产品公用模块（包含成品，统包，彩宝等）
        /// </summary>
        /// <param name="getInlaysParam">当前产品对应参数</param>
        /// <param name="requestUrl">产品请求URL</param>
        /// <returns></returns>
        public static string AllProduct(string getProductParam, string requestUrl,string key, string method = "post", bool isOriginalJson = false)
        {
             
            CommonConst.logParam = string.Format("getProductParam:{0}, requestUrl{1},  method{2} ,  isOriginalJson{3} ", getProductParam, requestUrl, method, isOriginalJson);
            method = method.ToLower();
            var msgInfo = "{\"msgcode\":#code,\"msginfo\":\"#msg\"}";
            try
            {
                //获取在线成品（含签名） 
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(getProductParam);
                var lastStr = "";
                if (method == "post" || method == "put")  //查询列表及新增,修改 才有参数需要签名
                    lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr.ToString(),key, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = getProductParam, RequestUrl = requestUrl };
                MyHttpRequest.RequestLib lib = new MyHttpRequest.RequestLib();
                switch (method)
                {
                    case "delete":
                        lib = MyHttpRequest.RequestLib.DELETE;
                        break;
                    case "put":
                        lib = MyHttpRequest.RequestLib.PUT;
                        break;
                    case "get":
                        lib = MyHttpRequest.RequestLib.GET;
                        break;
                    default:  //POST 
                        lib = MyHttpRequest.RequestLib.POST;
                        break;
                }
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, lib);
                return responseJson;
            }
            catch (Exception ex)
            {
                CommonLog.GetMethodInfoAndWriteLogs(type, ex);
                return string.Format(msgInfo, "false", "程序错误");
            }
        }

        /// <summary>
        /// 计算所有产品 的价格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <param name="productJson"></param>
        /// <param name="setting"></param>
        /// <returns></returns>
        private static T CalProductPrice<T>(HashParam param, string productJson, SystemSetting setting,string key)
        {
            dynamic product = JsonConvert.DeserializeObject<T>(productJson);
            //现货不计算价格
            if (!param.ContainsKey("IsStock") && !param.ContainsKey("IsMyStock")) //此处要多传一个IsStock或IsMyStock字段因为前段也可能搜索现货
            {
                decimal disc = setting.GetGlobalFancyDiscountReturn(); //全局折扣
                CustomerInfo customerInfo = new CustomerInfo();
                if (param.ContainsKey("CustomerID"))//客户折扣
                {
                    customerInfo = YZ.GetDatabase(key).Get<CustomerInfo>(Convert.ToInt32(param["CustomerID"]));
                    if (customerInfo.ParcelRebate != null && customerInfo.ParcelRebate.Value > 0)
                        disc = disc * customerInfo.ParcelRebate.Value;
                }
                //供应商折扣
                decimal supplierDisc = 0;
                //获取当前供应商折扣 
                supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,product.Supplier).ParcelRebate;
                if (supplierDisc != 0)
                    disc = disc * supplierDisc;
                //价格=全局，供应商，客户
                product.Price = product.Price * disc;
            }
            return product;
        }

        public static string GetGemIdsParamByCartInfoList(IList<Cart> cartInfoList)
        {
            StringBuilder sbIds = new StringBuilder();
            foreach (var item in cartInfoList)
            {
                sbIds.Append("\"" + item.GoodsID + "\",");
            }
            return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
        }
        public static string GetGemIdsParamByLendOrderList(IList<LendOrderResult> cartInfoList)
        {
            StringBuilder sbIds = new StringBuilder();
            foreach (var item in cartInfoList)
            {
                sbIds.Append("\"" + item.GoodsID + "\",");
            }
            return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
        }
        public static string GetGemIdsParamByLendOrderList(IList<LendOrderInfo> cartInfoList)
        {
            StringBuilder sbIds = new StringBuilder();
            foreach (var item in cartInfoList)
            {
                sbIds.Append("\"" + item.GoodsID + "\",");
            }
            return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
        }
        /// <summary>
        /// 获取折扣/退点
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="CustomerID"></param>
        /// <param name="supplierCode"></param>
        /// <returns></returns>
        public  decimal GetDiscount(string key,int goodType, int CustomerID, string supplierCode)
        {
            SysSettingInfo setting = GoodsType.GetSystemSetting(key, (int)goodType); 
            //客户折扣
            decimal customerDisc = 1;
            //供应商折扣
            decimal supplierDisc = 1;
          
            CustomerInfo customerInfo = YZ.GetDatabase(key).Get<CustomerInfo>(Convert.ToInt32(CustomerID));
            //客户优惠
            decimal disc = customerInfo.Discounts ?? 1;
           
            switch (goodType)
            {
                case GoodsType.Diamond:
                    customerDisc = customerInfo.Rebate ?? 1; break;
                case GoodsType.Ring:
                    customerDisc = customerInfo.RingRebate ?? 1; break;
                case GoodsType.Parcel:
                    customerDisc = customerInfo.ParcelRebate ?? 1; break;
                case GoodsType.Gem:
                    customerDisc = customerInfo.GemRebate ?? 1; break;
                case GoodsType.Emerald:
                    customerDisc = customerInfo.EmeraldRebate ?? 1; break;
                case GoodsType.PrimeGolds:
                    customerDisc = customerInfo.PrimeGoldRebate ?? 1; break;
            }
            switch (goodType)
            {
                case GoodsType.Diamond:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).Rebate ?? 1; break;
                case GoodsType.Ring:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).RingRebate ?? 1; break;
                case GoodsType.Parcel:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).ParcelRebate ?? 1; break;
                case GoodsType.Gem:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).GemRebate ?? 1; break;
                case GoodsType.Emerald:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).EmeraldRebate ?? 1; break;
                case GoodsType.PrimeGolds:
                    supplierDisc = DiamondsPriceHandlers.GetSuppliers(key,supplierCode).PrimeGoldRebate ?? 1; break;
            }
            if (disc == 0) disc = 1;
            if (supplierDisc == 0) supplierDisc = 1;
            if (customerDisc == 0) customerDisc = 1;
            var  result =  disc * customerDisc * supplierDisc;
            return result;
        }
        #endregion


        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes">默认 分钟</param>
        public static void SetCache(string key, string value, string minutes = "720")
        {
            int _minutes = 0;
            int.TryParse(minutes, out _minutes);
            //如果不设置默认10分钟
            HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddMinutes(_minutes == 0 ? 10 : _minutes), TimeSpan.Zero);
        }
    }
}

